package com.wsapi.module.role.service.impl;

import com.wsapi.commons.vo.Page;
import com.wsapi.commons.vo.PageList;
import com.wsapi.core.dao.RoleDao;
import com.wsapi.core.dao.model.SysRole;
import com.wsapi.core.dao.model.SysRolePerm;
import com.wsapi.module.role.service.RoleManagementService;
import java.util.HashSet;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import org.springframework.transaction.annotation.Transactional;

/**
 * 角色管理功能 User: yangyan Date: 14-1-2 Time: 下午9:45
 */
@Service
public class RoleManagementServiceImpl implements RoleManagementService {

    @Resource
    private RoleDao roleDao;

    @Override
    public PageList<SysRole> findByPage(Page page) {
        return this.roleDao.findByPage(page);
    }

    @Override
    public List<SysRole> findAll() {
        return this.roleDao.findAll();
    }

    @Transactional
    @Override
    public void addRole(SysRole role) {
        this.roleDao.save(role);
    }

    @Transactional
    @Override
    public void removeRole(SysRole role) {
        //先删除权限，再删除角色
        this.roleDao.execute("delete from SysRolePerm where role.roleId = ?", role.getRoleId());
        this.roleDao.delete(role);
        this.roleDao.flush();
    }

    @Transactional
    @Override
    public void updateRole(SysRole role) {
        this.roleDao.execute("delete from SysRolePerm where role.roleId = ?", role.getRoleId());
        SysRole old = this.roleDao.getById(role.getRoleId());
        this.roleDao.flush();
        old.getPermissions().addAll(role.getPermissions());
        old.setRoleExplain(role.getRoleExplain());
        old.setRoleName(role.getRoleName());
        this.roleDao.flush();
    }

    @Override
    public Set<String> getPermissionsByRoleId(Integer roleId) {
        List<SysRolePerm> permisionListByRoleId = this.roleDao.getPermisionListByRoleId(roleId);
        if (permisionListByRoleId == null) {
            return null;
        }
        Set<String> perms = new HashSet<>();
        for (SysRolePerm sysRolePerm : permisionListByRoleId) {
            perms.add(sysRolePerm.getPermKey());
        }
        return perms;
    }
}
